package alipaylogic

import (
	"github.com/gogap/logs"
	"github.com/shopspring/decimal"
	"go.uber.org/zap"
	"strconv"
	"time"
	"yundian/internel/app/dao"
	"yundian/internel/app/models/devices"
	"yundian/internel/app/models/membermodel"
	"yundian/internel/app/models/orders"
	"yundian/internel/app/models/placemodel"
	"yundian/internel/app/models/ploys"
	"yundian/internel/app/models/prices"
	"yundian/internel/app/models/users"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/wechatpay"
)

type AlipayOrderLogic struct {

}

func NewNotifyLogic() *AlipayOrderLogic {
	return &AlipayOrderLogic{}
}

func (al *AlipayOrderLogic) CreateOrder(respData *wechatpay.PayData, devInfo *devices.DeviceType, memInfo *membermodel.MembersModel) bool {
	ruleInfo := dao.NewPricesDao().GetPriceDetail(respData.Get("attach")).Unwrap().(*prices.PriceModel)
	ployInfo := dao.NewPloysDao().GetPlacePloyInfo(devInfo.PlaceId, devInfo.SharedMode).Unwrap().(*ploys.PloyModel) // 获取商户最新奖励规则配置

	var money int64
	if devInfo.FeeMode == 1 {
		money = ruleInfo.Deposit
	} else { // 套餐
		money = ruleInfo.PayMoney
	}
	dtAmount := wechatpay.NewPayData()
	_ = dtAmount.FromJsonStr(respData.Get("amount"))
	// 验证订单价格是否正确
	wxMoney, _ := strconv.Atoi(dtAmount.Get("total"))
	if int64(wxMoney) != money {
		logs.Info("打印测试数据，价格不一致")
		zap.L().Error("微信支付结果通知,价格不一致")
		return true
	}
	payMoney, _ := strconv.ParseInt(dtAmount.Get("payer_total"), 10, 64)

	//stamp, _ := time.ParseInLocation("20060102150405", respData.Get("time_end"), time.Local)
	//stampSuccessTime, _ := time.Parse("2006-01-02T15:04:05+08:00", respData.Get("success_time"))
	var bjlocal = time.FixedZone("Asia/Shanghai", 8*60*60)
	stampSuccessTime, _ := time.ParseInLocation("2006-01-02T15:04:05+08:00", respData.Get("success_time"), bjlocal)

	var uInfo *users.UserModel
	var isDraw, isTianhai int
	placeInfo := dao.NewPlaceDao().GetPlaceById(devInfo.PlaceId).Unwrap().(*placemodel.PlaceModel)     // 获取网点详情
	userInfo := dao.NewUserDao().GetUserInfoByPlaceId(devInfo.PlaceId).Unwrap().(*users.UserModel) // 获取用户详情
	uInfo = dao.GetParentUserInfoById(userInfo)
	isDraw = NewNotifyLogic().PloyWxOrderNoSmallDraw(memInfo, ployInfo, placeInfo)
	if isDraw == 1 {
		if uInfo.ID == 0 { // 代理商被删除，不存在
			uInfo = dao.NewUserDao().GetUserInfoById(2).Unwrap().(*users.UserModel)
		} else {
			u := dao.GetLastDrawUserInfo(uInfo)                                  // 获取开启权益的用户
			if u.ParentID == 0 && u.IsAdmin == 2 && placeInfo.BranchUserId > 0 { // 代理商都没开启
				uInfo = dao.NewUserDao().GetUserInfoById(placeInfo.BranchUserId).Unwrap().(*users.UserModel)
			} else {
				uInfo = u
			}
		}
	}

	// 1:等待下单2:使用中3:已撤销4:交易失败5:已完成6:支付超时7:待守约10:已删除
	var status int8
	switch respData.Get("trade_state") {
	case "SUCCESS":
		status = 2 // SUCCESS—支付成功  工作中
	case "REFUND":
		status = 11 // REFUND—转入退款
	case "NOTPAY":
		status = 1 // NOTPAY—未支付
	case "CLOSED":
		status = 9 // CLOSED—已关闭
	case "REVOKED":
		status = 3 // REVOKED—已撤销（刷卡支付）
	case "USERPAYING":
		status = 8 // USERPAYING--用户支付中
	case "PAYERROR":
		status = 4 // PAYERROR--支付失败(其他原因，如银行返回失败)
	}

	var payForm int8
	if respData.Get("trade_type") == "JSAPI" || respData.Get("trade_type") == "Normal" {
		payForm = 2
	}
	if respData.Get("trade_type") == "PreAuthPay" {
		payForm = 1
	}

	payerDt := wechatpay.NewPayData()
	_ = payerDt.FromJsonStr(respData.Get("payer"))
	m := orders.New().Mutate(
		orders.WithAppid(respData.Get("appid")),
		orders.WithDeviceSn(devInfo.DeviceSn),
		orders.WithMchid(respData.Get("mchid")),
		orders.WithOpenid(payerDt.Get("openid")),
		orders.WithOutTradeNo(respData.Get("transaction_id")), // 微信订单号
		orders.WithTradeNo(respData.Get("out_trade_no")),      // 商户订单号
		orders.WithProductId(respData.Get("attach")),

		orders.WithMemberId(memInfo.UUID),
		orders.WithMemberName(memInfo.NickName),
		orders.WithMemberPhone(memInfo.Phone),
		orders.WithPlaceId(devInfo.PlaceId),
		orders.WithPlaceName(devInfo.PlaceName),
		orders.WithSharedMode(devInfo.SharedMode),
		orders.WithFeeMode(int8(devInfo.FeeMode)),

		orders.WithMoney(money),
		orders.WithMoneyStr(decimal.NewFromInt(money).Div(decimal.NewFromInt(100)).StringFixed(2)),
		orders.WithPayMoney(payMoney),
		orders.WithPayMoneyStr(decimal.NewFromInt(payMoney).Div(decimal.NewFromInt(100)).StringFixed(2)),

		orders.WithState(status),
		orders.WithTradeType(respData.Get("trade_type")), // 订单支付类型
		orders.WithTradeState(respData.Get("trade_state")),          // 微信交易 状态
		orders.WithTradeStateDesc(respData.Get("trade_state_desc")), // 微信交易状态描述
		orders.WithPayType(3),
		orders.WithSettlementWay(1), // 未结算
		orders.WithOrderFrom("weixin"),
		orders.WithPayFrom(payForm), // 1免押 2押金

		orders.WithPayAt(dingo.Time(stampSuccessTime.Unix())),            // 支付时间
		orders.WithBeginAt(dingo.Time(time.Now().Unix())),
		orders.WithCreateAt(dingo.Time(time.Now().Unix())),


		orders.WithIsDraw(int8(isDraw)), // 1抽单 0不抽单
		orders.WithIsTianHai(int8(isTianhai)), // 0新系统  1天海

		orders.WithUserId(userInfo.ID),
		orders.WithUserName(userInfo.Name),
		orders.WithParentId(userInfo.ParentID),
		orders.WithKaUserId(userInfo.BranchUserId),
		orders.WithAgentUserId(uInfo.ID),
		orders.WithProdType(devInfo.ProdType), // 设备类型  1  2  3

	)
	if ok := dao.NewOrderDao().InsertOrder(m).Unwrap().(bool); ok { // 订单入库成功
		return true
	}
	return false
}
